package com.demo.ohos_zblibrary;

import com.demo.ohos_zblibrary.tool.IntentUtil;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Image;
import ohos.agp.components.Text;
import ohos.agp.window.dialog.ToastDialog;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import zuo.biao.library.util.CommonUtil;
import zuo.biao.library.util.Log;

import java.io.*;

/**
 * 展示拍照后的图片
 */
public class ShowCameraPhotoAbility extends Ability {
    private static final int PHOTOCODE = 1221;

    Image image;
    Text txt_show;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_ability_show_camera_photo);
        Button button = (Button) findComponentById(ResourceTable.Id_btn_open);
        button.setClickedListener(component -> openCamera());
        image = (Image) findComponentById(ResourceTable.Id_img_show);
        txt_show = (Text) findComponentById(ResourceTable.Id_txt_show);
    }

    private void openCamera() {
        IntentUtil.toActivity(this, "CameraAbility", PHOTOCODE);
    }

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
        super.onAbilityResult(requestCode, resultCode, resultData);
        if (requestCode == PHOTOCODE) {
            if (resultData != null) {
                String path = resultData.getStringParam("data");
                if (path == null) {
                    CommonUtil.showShortToast(this,"path is null,请使用手机");
                    return;
                }
                txt_show.setText(path);

                File file = new File(path);
                InputStream inputStream = null;
                PixelMap bitmap = null;
                try {
                    inputStream = new BufferedInputStream(new FileInputStream(file));
                    bitmap = ImageSource.create(inputStream, new ImageSource.SourceOptions()).createPixelmap(null);
                    image.setPixelMap(bitmap);
                } catch (FileNotFoundException e) {
                    Log.error("FileNotFoundException",e.getMessage());
                }finally {
                    if (inputStream != null) {
                        try {
                            inputStream.close();
                        } catch (IOException e) {
                            Log.error("IOException",e.getMessage());
                        }
                    }
                }
            }
        }
    }

    private void toastMag(String msg) {
        new ToastDialog(this).setContentText(msg).show();
    }
}
